package com.winona.util;

import org.json.JSONObject;

import android.text.TextUtils;

import com.taplinker.core.util.json.JsonUtil;
import com.winona.bean.AiterResponse;

public class ResponseUtil {
	
	/**
	 * body is String
	 * @param json
	 * @return
	 */
	public static AiterResponse getResponseStringFromJson(String json) {
		if (TextUtils.isEmpty(json)) {
			return null;
		}
		AiterResponse resp = null;
		try {
			resp = new AiterResponse();
			JSONObject jo = new JSONObject(json);
			resp.setCode(jo.getString("code"));
			resp.setMessage(jo.getString("message"));
			JSONObject obj = jo.getJSONObject("body");
			if (obj != null) {
				resp.setBody(jo.getJSONObject("body").toString());
			} else {
				resp.setBody(null);
			}
			return resp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 *  body is list
	 * @param json
	 * @return
	 */
	public static AiterResponse getResponseListFromJson(String json) {
		if (TextUtils.isEmpty(json)) {
			return null;
		}
		AiterResponse resp = null;
		try {
			resp = new AiterResponse();
			JSONObject jo = new JSONObject(json);
			resp.setCode(jo.getString("code"));
			resp.setMessage(jo.getString("message"));
			JSONObject obj = jo.getJSONObject("body");
			if (obj != null) {
				resp.setBody(jo.getJSONArray("body").toString());
			} else {
				resp.setBody(null);
			}
			return resp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * body is object of bodyClass
	 * @param json
	 * @param bodyClass
	 * @return
	 */
	public static AiterResponse getResponseObjFromJson(String json, Class<?> bodyClass) {
		if (TextUtils.isEmpty(json)) {
			return null;
		}
		if (bodyClass == null) {
			bodyClass = String.class;
		}
		AiterResponse resp = null;
		try {
			resp = new AiterResponse();
			JSONObject jo = new JSONObject(json);
			resp.setCode(jo.getString("code"));
			resp.setMessage(jo.getString("message"));
			JSONObject obj = jo.getJSONObject("body");
			if (obj != null) {
				resp.setBody(JsonUtil.jsonToObject(jo.getJSONObject("body").toString(), bodyClass));
			} else {
				resp.setBody(null);
			}
			return resp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
